<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\index\logic;

/**
 * 会员逻辑
 */
class User extends IndexBase
{
    /**
     * 获取简历列表
     */
    public function getResumeList($where = [], $field = 'a.*,b.username ,b.headimg', $order = 'a.update_time desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelResume->alias('a');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'a.user_id = b.id', 'LEFT'],
        ];

        $where['a.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelResume->join = $join;

        return $this->modelResume->getList($where, $field, $order, $paginate);
    }
    /**
     * 冻结团队
     */
    public function frozenUser($data)
    {
        $nocodea=db('user')->where(array('username'=>$data['username']))->value('id');
        if(empty($nocodea)){
            return [RESULT_ERROR, '不存在该用户'];
        }else{
            if($data['dj'] == 1){
                $msg=array('status'=>0);
            }else{
                $msg=array('status'=>1);
            }
            $result=db('user')->where("id=".$nocodea." or nocodea like '%$nocodea%'")->update($msg);
            $result && action_log('冻结用户团队', '冻结用户团队，username：' . $data['username']);
            if($result){
                echo json_encode(array('code'=>0,'msg'=>'操作成功'));exit;
            }else{
                echo json_encode(array('code'=>1,'msg'=>'操作失败'));exit;
            }
        }
    }
    
    /**
     * 获取会员信息
     */
    public function getUserInfo($where = [], $field = true)
    {
        
        $info = $this->modelUser->getInfo($where, $field);

        return $info;
    }
    /**
     * 导出会员列表
     */
    public function exportUserList($where = [], $field = 'm.*,b.username as tjusername,b.name as tjname', $order = '')
    {
        
        $list = $this->getUserList($where, $field, $order, false);
        
        $titles = "昵称,用户名,手机,注册时间,上级";
        $keys   = "name,username,phone,create_time,tjusername";
        
        action_log('导出', '导出用户列表');
        
        export_excel($titles, $keys, $list, '用户列表');
    }	
    /**
     * 获取会员列表
     */
    public function getUserList($where = [], $field = 'm.*,b.username as tjusername,b.name as tjname', $order = 'id asc', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelUser->alias('m');
        
        $join = [
                    [SYS_DB_PREFIX . 'user b', 'm.tjid = b.id', 'LEFT'],
                ];
        
        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        $this->modelUser->join = $join;
        
        return $this->modelUser->getList($where, $field, $order, $paginate);
    }
	/**
     * 获取会员列表搜索条件
     */
    public function getWhere($data = [])
    {
        
        $where = [];
        !empty($data['search_data']) && $where['m.name|m.username|m.phone|m.sbh'] = ['like', '%'.$data['search_data'].'%'];
        !empty($data['tjid']) && $where['m.tjid']=$data['tjid'];
		!empty($data['is']) && $where['m.is']=$data['is'];
        !empty($data['gsrz']) && $where['m.gsrz']=$data['gsrz'];
        return $where;
    }
    
    /**
     * 会员添加
     */
    public function userAdd($data = [])
    {
        
        $validate_result = $this->validateUser->scene('add')->check($data);
        
        if (!$validate_result) {
            
            return [RESULT_ERROR, $this->validateUser->getError()];
        }
        
        $url = url('userList');
        
        $info=db("user")->field("id,nocodea")->where('username',$data['tjusername'])->find();
		if(empty($info)){
			return [RESULT_ERROR, '不存在该分享人'];
		}
		$data['tjid']=$info['id'];
		$data['nocodea'] = $info['nocodea'].$data['tjid'].',';
		$data['password'] = data_md5_key($data['password']);
        $result = $this->modelUser->setInfo($data);
		//$nocodea=$info['nocodea'].$result.',';
		//$res=db('user')->where('id',$result)->update(array('nocodea'=>$nocodea));
        $result && action_log('新增', '新增用户，username：' . $data['username']);
        
        return $result ? [RESULT_SUCCESS, '用户添加成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 会员编辑
     */
    public function userEdit($data = [])
    {
        
        $validate_result = $this->validateUser->scene('edit')->check($data);
        
        if (!$validate_result) {
            
            return [RESULT_ERROR, $this->validateUser->getError()];
        }
        $url = url('userList');
        if($data['tjuser'] != $data['tjusername']){
            $info=db('user')->field('id,name,nocodea')->where('username',$data['tjusername'])->find();
            if(empty($info)){
                return [RESULT_ERROR, '不存在该分享人'];
            }
            if($info['id'] == $data['id']){
                return [RESULT_ERROR, '分享人不能为本人'];
            }else{
                $arr=explode(',',$info['nocodea']);
                if(in_array($data['id'],$arr)){
                    return [RESULT_ERROR, '该用户为自己团队人员，不能作为分享人'];
                }
            }
            db('user')->startTrans();
            $nocodea=db('user')->where('id',$data['id'])->value('nocodea');
            $data['tjid']=$info['id'];
            $data['nocodea']=$info['nocodea'].$info['id'].',';
            $result = $this->modelUser->setInfo($data);
            $str=','.$data['id'].',';
            $list=db('user')->field('id,nocodea')->where("nocodea like '%$str%'")->select();
            if(!empty($list)){
                foreach($list as $k=>$v){
                    $thnocodeas=$info['nocodea'].$info['id'].',';
                    $str1=str_replace($nocodea,$thnocodeas,$v['nocodea']);
                    $res=db('user')->where('id',$v['id'])->update(array('nocodea'=>$str1));
                }
            }else{
                $res =true;
            }
            if($result && $res){
                db('user')->commit();
                action_log('编辑', '编辑用户，id：' . $data['id'].'；分享人变动：'.$data['tjuser'].'=>'.$data['tjusername']);
            }else{
                db('user')->rollback();
            }
        }else{
            $result = $this->modelUser->setInfo($data);
            $result && action_log('编辑', '编辑用户，id：' . $data['id']);
        }
        return $result ? [RESULT_SUCCESS, '用户编辑成功', $url] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    /**
     * 公司信息编辑
     */
    public function companyEdit($data = [])
    {
        $validate_result = $this->validateCompany->scene('company')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateCompany->getError()];
        }
        $url = url('companyList');
        $result = db('company')->where('company_id',$data['company_id'])->update($data);
        $result && action_log('编辑', '编辑公司信息，company_id：' . $data['company_id']);
        return $result ? [RESULT_SUCCESS, '公司信息编辑成功', $url] : [RESULT_ERROR, $this->modelCompany->getError()];
    }
    /**
     * 设置会员信息
     */
    public function setMemberValue($where = [], $field = '', $value = '')
    {
        
        return $this->modelMember->setFieldValue($where, $field, $value);
    }
	/**
     * 导出公司列表
     */
    public function exportCompanyList($where = [], $field = 'm.*,b.username,b.name', $order = 'company_id desc')
    {
        
        $list = $this->getCompanyList($where, $field, $order, false);
        
        $titles = "公司名称,用户名,法人,联系人,联系电话,时间";
        $keys   = "company,username,person,persons,phone,create_time";
        
        action_log('导出', '导出公司认证申请');
        
        export_excel($titles, $keys, $list, '公司认证申请列表');
    }
    /**
     * 获取会员列表
     */
    public function getCompanyList($where = [], $field = 'm.*,b.username,b.name', $order = 'm.stat asc,m.company_id desc', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelCompany->alias('m');
        
        $join = [
                    [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
                ];
        
        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        $this->modelCompany->join = $join;
        $list=$this->modelCompany->getList($where, $field, $order, $paginate);
		foreach($list as $k=>$v){
			if(!empty($v['imgs'])){
				$list[$k]['imgs']=explode(',',substr($v['imgs'],0,-1));
			}			
		}
        return $list;
    }
    /**
     * 获取会员动态列表
     */
    public function getTrendList($where = [], $field = 'm.*,b.username,b.name', $order = '', $paginate = DB_LIST_ROWS)
    {

        $this->modelTrend->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelTrend->join = $join;
        $list=$this->modelTrend->getList($where, $field, $order, $paginate);
        return $list;
    }
    /**
     * 获取会员动态列表
     */
    public function getSuggestList($where = [], $field = 'm.*,b.username,b.name', $order = '', $paginate = DB_LIST_ROWS)
    {

        $this->modelSuggest->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelSuggest->join = $join;
        $list=$this->modelSuggest->getList($where, $field, $order, $paginate);
        return $list;
    }
    /**
     * 获取会员动态列表
     */
    public function getReportList($where = [], $field = 'm.*,b.username,b.name', $order = '', $paginate = DB_LIST_ROWS)
    {

        $this->modelReport->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelReport->join = $join;
        $list=$this->modelReport->getList($where, $field, $order, $paginate);
        return $list;
    }
	/**
     * 获取代理申请列表
     */
    public function getApplyList($where = [], $field = 'm.*,b.username,b.name', $order = '', $paginate = DB_LIST_ROWS)
    {
        
        $this->modelApply->alias('m');
        
        $join = [
                    [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
                ];
        
        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        $this->modelApply->join = $join;
        $list=$this->modelApply->getList($where, $field, $order, $paginate);
        return $list;
    }
	/**
     * 获取会员列表搜索条件
     */
    public function getWheres($data = [])
    {
    	$add=db('service')->where('user_id',USER_ID)->value('code');
    	$address=db('region')->where('code',$add)->value('name');
        $where = [];
        !empty($address) && $where['m.address']=$address;
        isset($data['stat']) && $data['stat']!=9 && $where['m.stat']=$data['stat'];
        !empty($data['search_data']) && $where['m.company|b.username|b.name'] = ['like', '%'.$data['search_data'].'%'];        
        //!empty($data['tjid']) && $where['m.tjid']=$data['tjid'];
        return $where;
    }
	/**
     * 余额明细
     */
    public function getMoneyyjList($data)
    {
        $where = [];     
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        isset($data['type']) && $where['type'] = $data['type'];
        !empty($data['search_data']) && $where['user_id'] = ['like', '%'.$data['search_data'].'%'];
        return $this->modelMoneyyj->getList($where,'*','id DESC');
    }
	/**
     * 权限明细
     */
    public function getLogList($data)
    {
        $where = [];     
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
		isset($data['type']) && $where['type'] = $data['type'];
        !empty($data['key']) && $where['key'] = $data['key'];
        !empty($data['search_data']) && $where['user_id'] = ['like', '%'.$data['search_data'].'%'];
        return $this->modelLog->getList($where,'*','id DESC');
    }
    /**
     * 服务商列表
     */
    public function getAgentList($where = [], $field = 'm.*,b.username,b.name', $order = 'm.create_time desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelAgent->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelAgent->join = $join;
        $list=$this->modelAgent->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
            $list[$k]['address']=db('region')->where('code',$v['code'])->value('name');
        }
        return $list;
    }
    /**
     * 服务商列表
     */
    public function getServiceList($where = [], $field = 'm.*,b.username,b.name as names', $order = 'm.create_time desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelService->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelService->join = $join;
        $list=$this->modelService->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
            $list[$k]['addresss']=db('region')->where('code',$v['code'])->value('name');
        }
        return $list;
    }
    /**
     * 服务商添加
     */
    public function serviceAdd($data = [])
    {
        $url = url('serviceList');
        if(empty($data['id'])){
            if (empty($data['username']) || empty($data['name']) || empty($data['addresss'])) {
                return [RESULT_ERROR, '请输入完整信息'];
            }else{
                $user_id=db('user')->where('username',$data['username'])->value('id');
                if(empty($user_id)){
                    return [RESULT_ERROR, '请输入正确用户名'];
                }
                $is=db('service')->where('user_id',$user_id)->value('id');
                if(!empty($is)){
                    return [RESULT_ERROR, '请用户已成为服务商，不能重复提交'];
                }
                $a=$data['addresss'];
                $region=db('region')->field('code,level')->where("name like '%$a%'")->find();
                if(empty($region)){
                    return [RESULT_ERROR, '没有查询到该地址'];
                }
                $is=db('service')->where('code',$region['code'])->value('id');
                if(!empty($is)){
                    return [RESULT_ERROR, '该地区已存在服务商，请选择其他区域'];
                }
            }
            $data['user_id']=$user_id;
            $data['code']=$region['code'];
            $data['level']=$region['level'];
            $data['create_time']=time();
            $res=db('service')->insertGetId($data);
            $res && action_log('新增', '新增服务商，id：' . $res);
            db('user')->where('id',$user_id)->update(array('is_service'=>1));
        }else{
            $a=$data['addresss'];
            $region=db('region')->field('code,level')->where("name like '%$a%'")->find();
            if(empty($region)){
                return [RESULT_ERROR, '没有查询到该地址'];
            }
            $is=db('service')->where("id!=".$data['id']." and code=".$region['code'])->value('id');
            if(!empty($is)){
                return [RESULT_ERROR, '该地区已存在服务商，请选择其他区域'];
            }
            $data['code']=$region['code'];
            $data['level']=$region['level'];
            $res=db('service')->where('id',$data['id'])->update($data);
            $res && action_log('编辑', '编辑服务商信息，id：' . $data['id']);
        }
        return $res ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, '操作失败'];
    }
    /**
     * 获取会员列表
     */
    public function getChatList($where = [], $field = 'm.*,b.username,b.name,b.headimg,b.is_service,b.is,b.gsrz,b.id as resume', $order = 'm.create_time desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelChat->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.getid = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelChat->join = $join;

        return $this->modelChat->getList($where, $field, $order, $paginate);
    }
    /**
     * 获取会员列表
     */
    public function getChatLists($where = [], $field = 'm.*,b.username,b.name,b.headimg,b.is_service,b.is,b.gsrz,b.id as resume', $order = 'm.create_time desc', $paginate = DB_LIST_ROWS)
    {

        $this->modelChat->alias('m');

        $join = [
            [SYS_DB_PREFIX . 'user b', 'm.user_id = b.id', 'LEFT'],
        ];

        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelChat->join = $join;

        return $this->modelChat->getList($where, $field, $order, $paginate);
    }
    /**
     * 获取会员列表
     */
    public function getShoucangList($where = [], $field = '*', $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        $list=$this->modelShoucang->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
            $user_id=db('resume')->where('resume_id',$v['resume_id'])->value('user_id');
            $info=db('user')->field('username,name,headimg,gsrz,is,is_service')->where('id',$user_id)->find();
            $list[$k]['username']=$info['username'];
            $list[$k]['name']=$info['name'];
            $list[$k]['headimg']=$info['headimg'];
            $list[$k]['gsrz']=$info['gsrz'];
            $list[$k]['is']=$info['is'];
            $list[$k]['resume']=$user_id;
            $list[$k]['is_service']=$info['is_service'];
        }
        return $list;
    }
    /**
     * 获取会员列表
     */
    public function getInterviewList($where = [], $field = '*', $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        $list=$this->modelInterview->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
            $info=db('user')->field('username,name,headimg,gsrz,is,is_service')->where('id',$v['getid'])->find();
            $list[$k]['username']=$info['username'];
            $list[$k]['name']=$info['name'];
            $list[$k]['headimg']=$info['headimg'];
            $list[$k]['gsrz']=$info['gsrz'];
            $list[$k]['is']=$info['is'];
            $list[$k]['resume']=$v['getid'];
            $list[$k]['is_service']=$info['is_service'];
        }
        return $list;
    }
    /**
     * 获取会员列表
     */
    public function getUsersList($where = [], $field = 'm.*,b.resume_id', $order = 'm.id desc', $paginate = DB_LIST_ROWS)
    {
        $this->modelUser->alias('m');
        $join = [
            [SYS_DB_PREFIX . 'resume b', 'm.id = b.user_id', 'LEFT'],
        ];
        $where['m.' . DATA_STATUS_NAME] = ['neq', DATA_DELETE];

        $this->modelUser->join = $join;

        return $this->modelUser->getList($where, $field, $order, $paginate);
    }
    /**
     * 获取投递用户列表
     */
    public function getResumeLists($where = [], $field = '*', $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        $list=$this->modelDeliverResume->getList($where, $field, $order, $paginate);
        foreach($list as $k=>$v){
            $info=db('user')->field('username,name,headimg,gsrz,is,is_service')->where('id',$v['user_id'])->find();
            $list[$k]['username']=$info['username'];
            $list[$k]['name']=$info['name'];
            $list[$k]['headimg']=$info['headimg'];
            $list[$k]['gsrz']=$info['gsrz'];
            $list[$k]['is']=$info['is'];
            $list[$k]['resume']=$v['user_id'];
            $list[$k]['is_service']=$info['is_service'];
        }
        return $list;
    }
}
